<?php
/**
 * Date: 2024.8
 * Author: kahn
 */
namespace service\uc;

use cache\CaptchaCache;
use Gregwar\Captcha\CaptchaBuilder;

class CaptchaService
{
    static function isOpen()
    {
        return \Yaf_Registry::get('config')->captcha->on == 1;
    }

    /**
     * @param $uniqueId
     * @param $img64
     * @return bool
     */
    static function generate(&$uniqueId, &$img64): bool
    {
        //$code = (new Captcha())->getCode();
        //$img64 = (New Captcha())->generateBase64($code);

        $captcha = new CaptchaBuilder(4);
        $code =  $captcha->getPhrase();
        $captcha->build(140, 45);
        $img64 = base64_encode($captcha->get());
        $uniqueId = self::uniqueId();
        //缓存二维码code
        if(!(new CaptchaCache())->setCaptcha($code, $uniqueId)){
            return false;
        }

        return true;
    }

    /*
     * 生成图片验证码的唯一id
     */
    static function uniqueId(): string
    {
        return md5(uniqid(md5(microtime(true)),true) . mt_rand(1111, 9999));
    }

    /*
     * 换成图片验证码
     */
    static function cacheCode($code, $uniqueId){
        return ;
    }

    //设置需要验证的手机号
    static function setInVerify($mobile){
        (new CaptchaCache())->setInVerify($mobile);
    }

    //验证图片验证码
    static function verify($mobile, $code, $uniqueId): bool
    {
        if(!self::isOpen()){ //如果关闭了图片验证码功能, 直接返回
            return true;
        }

        $cd = new CaptchaCache();

        //如果该手机号不需要图片验证码验证, 则返回通过
        if (!$cd->isInVerify($mobile)){
            return true;
        }

        //需要图片验证码但是没收到相关参数
        if(!$code || !$uniqueId){
            return false;
        }

        $cacheCode = $cd->getCaptcha($uniqueId);
        if(!$cacheCode){ //验证码已过有效期
            return false;
        }

        //验证码不匹配
        if(strtoupper($cacheCode) != strtoupper($code)){
            return false;
        }

        return true;
    }


}